package com.rfs.suanfa;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;

/**
 * @author renfushuai
 * @date 2022/2/9
 */
public class 两数之和 {
    public static void main(String[] args) {
        int[] nums = new int[]{3,2,4};
        int target = 6;
        int[] ints = twoSum(nums, target);
        System.out.println(JSON.toJSONString(ints));
    }

    public static int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                return res;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}
